package com.yikaiye.android.yikaiye.utils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.yikaiye.android.yikaiye.utils.sharedpreference.SPUtil;

import java.util.Iterator;
import java.util.List;

public class SearchHistoryUtil {

    /**
     * 保存搜索记录到本地
     *
     * @param keyWord 搜索关键字
     */
    public static void saveKeyWord(String keyWord) {
        String json = SPUtil.getString("history", "[]");
        JsonArray jsonArray = new JsonParser().parse(json).getAsJsonArray();
        Gson gson = new Gson();
        List<String> list = gson.fromJson(jsonArray, new TypeToken<List<String>>() {
        }.getType());
        list.removeIf(keyWord::equals);
        list.add(0, keyWord);
        if (list.size() > 10) {
            list.remove(list.size() - 1);
        }
        SPUtil.put("history", new Gson().toJson(list));
    }

    /**
     * 获取本地搜索记录
     *
     * @return list
     */
    public static List<String> getHistory() {
        String history = SPUtil.getString("history", "[]");
        JsonArray jsonArray = new JsonParser().parse(history).getAsJsonArray();
        Gson gson = new Gson();
        return gson.fromJson(jsonArray, new TypeToken<List<String>>() {
        }.getType());
    }

    /**
     * 清空搜索记录
     */
    public static void cleanHistory() {
        SPUtil.put("history", "[]");
    }

    /**
     * 保存搜索记录到本地(企业)
     *
     * @param keyWord 搜索关键字
     */
    public static void saveCompanyKeyWord(String keyWord) {
        String json = SPUtil.getString("companyHistory", "[]");
        JsonArray jsonArray = new JsonParser().parse(json).getAsJsonArray();
        Gson gson = new Gson();
        List<String> list = gson.fromJson(jsonArray, new TypeToken<List<String>>() {
        }.getType());
        list.removeIf(keyWord::equals);
        list.add(0, keyWord);
        if (list.size() > 10) {
            list.remove(list.size() - 1);
        }
        SPUtil.put("companyHistory", new Gson().toJson(list));
    }

    /**
     * 获取本地搜索记录
     *
     * @return list
     */
    public static List<String> getCompanyHistory() {
        String history = SPUtil.getString("companyHistory", "[]");
        JsonArray jsonArray = new JsonParser().parse(history).getAsJsonArray();
        Gson gson = new Gson();
        return gson.fromJson(jsonArray, new TypeToken<List<String>>() {
        }.getType());
    }

    /**
     * 清空搜索记录
     */
    public static void cleanCompanyHistory() {
        SPUtil.put("companyHistory", "[]");
    }
}
